from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class Item(db.Model):
    """物品类模型"""
    __tablename__ = 'items'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False, unique=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系：作为源物品的关系
    source_relations = db.relationship('Relation', foreign_keys='Relation.source_item_id', backref='source_item', lazy='dynamic', cascade='all, delete-orphan')
    # 关系：作为目标物品的关系
    target_relations = db.relationship('Relation', foreign_keys='Relation.target_item_id', backref='target_item', lazy='dynamic', cascade='all, delete-orphan')
    
    def __init__(self, name):
        self.name = name
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'name': self.name,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<Item {self.id}: {self.name}>'


class Relation(db.Model):
    """关系类模型"""
    __tablename__ = 'relations'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    source_item_id = db.Column(db.Integer, db.ForeignKey('items.id', ondelete='CASCADE'), nullable=False)
    target_item_id = db.Column(db.Integer, db.ForeignKey('items.id', ondelete='CASCADE'), nullable=False)
    relation_type = db.Column(db.String(100), default='related_to')  # 关系类型，如 "is_a", "part_of", "related_to" 等
    description = db.Column(db.Text)  # 关系描述
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 确保同一对物品之间的同类型关系不重复
    __table_args__ = (
        db.UniqueConstraint('source_item_id', 'target_item_id', 'relation_type', name='unique_relation'),
    )
    
    def __init__(self, source_item_id, target_item_id, relation_type='related_to', description=None):
        self.source_item_id = source_item_id
        self.target_item_id = target_item_id
        self.relation_type = relation_type
        self.description = description
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'source_item_id': self.source_item_id,
            'target_item_id': self.target_item_id,
            'source_item_name': self.source_item.name if self.source_item else None,
            'target_item_name': self.target_item.name if self.target_item else None,
            'relation_type': self.relation_type,
            'description': self.description,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<Relation {self.id}: {self.source_item_id} -> {self.target_item_id} ({self.relation_type})>'
